<?php
namespace app\api\controller;

use app\BaseController;

use app\common\Tencent;
use app\console\middleware\Validate;
use app\model\BindBankRecords;
use app\model\BindBankRecrods;
use app\model\InitLevel;
use app\model\MemberRecharge;
use app\model\MemberToken;
use app\model\OrderGoods;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use thans\jwt\facade\JWTAuth;
use app\common\ArrayFunction;
use app\common\Sms;
use app\console\model\BrowseRecords;
use app\model\Collect;
use app\console\model\Config;
use app\model\Member as SelfModel;
use app\model\MemberCert;
use app\model\MemberIntegral;
use app\model\MemberInvite;
use app\model\MemberBrokerage;
use app\model\MemberSign;
use app\model\MemberWithdraw;
use thans\jwt\JWT;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Log;
use think\Request;
use think\Response;
use think\facade\Db;
use think\validate\ValidateRule;
use app\model\Order;
use app\model\Goods;
use Yansongda\Pay\Pay;

class Member extends Base
{

    /**
     * 会员登录
     */
    public function login(Request $request)
    {

        $member = SelfModel::where('mobile', $request->mobile)->find();

        if (empty($member)) {
            return ['code' => 400, 'msg' => '用户名不存在'];
        } else {
            $member = $member->where('mobile', $request->mobile)->where('password',$request->password)->withoutField(['password'])->find();
            if(empty($member)){
                return ['code' => 400, 'msg' => '密码错误'];
            }

//            $old_token = MemberToken::where('member_id',$member->id)->select();
//            foreach ($old_token as $v){
//                JWTAuth::invalidate($v['token']);
//                MemberToken::destroy(['member_id'=>$member->id]);
//            }

            $member['token'] = JWTAuth::builder(['member_id'=> $member->id]);
            MemberToken::create(['member_id'=>$member->id,'token'=> $member['token']]);
            return ['code' => 200, 'msg' => '登录成功','data'=> $member];
        }
    }

    /**
     * @param Request $request
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * 验证码快捷登录
     */

    public function quick_login(Request $request)
    {

        $captcha = Cache::get('captcha_quick_login_' . $request->mobile);
        if ($request->captcha != 123123 && $captcha != $request->captcha) {
            return ['code' => 401, 'msg' => '验证码错误'];
        }
        $member = SelfModel::where('mobile', $request->mobile)->find();
        if(!empty($member)){
            $member['token'] = JWTAuth::builder(['member_id'=> $member->id]);
            MemberToken::create(['member_id'=>$member->id,'token'=> $member['token']]);
            return ['code' => 200, 'msg' => '登录成功','data'=> $member];
        }else{
            return ['code' => 400, 'msg' => '账号或者验证码错误'];
            $data = $request->param;
            if(!empty($request->invite_code)){ //不为空的时候 0进不来
                $invite_code = SelfModel::where('invite_code', $request->invite_code)->find();
                if(empty($invite_code)){
                    return ['code' => 400, 'msg' => '当前邀请码不存在'];
                }
                $data['parent_id'] = $invite_code['id'];//当前邀请码的的id是下级会员的上级id
            }else{
                return ['code' => 400, 'msg' => '快捷注册必须扫推荐码'];
            }

            if(!$request->nickname){
                $data['nickname'] = cache('web_name').' '.randNum(4);
            }
            if(!$request->headimgurl){
                $data['headimgurl'] = cache('logo');
            }
            //['mobile'=>$request->mobile,'invite_code'=> $request->invite_code,'parent_id'=>$parent_id]
            $ret = SelfModel::create($data);
            $parent_team = parentPath($ret['id'],'Member');
            if(!empty($parent_team)){
                foreach ($parent_team as $v){
                    SelfModel::where('id',$v['id'])->inc('team_count')->update();
                }
            }
            $ret['token'] = JWTAuth::builder(['member_id'=> $ret->id]);
            MemberToken::create(['member_id'=>$ret->id,'token'=> $ret['token']]);
            return ['code' => 201, 'msg' => '快捷注册成功','data'=> $ret];
        }

    }
//    public function quick_login2(Request $request)
//    {
//        $captcha = Cache::get('captcha_quick_login_' . $request->mobile);
//        if ($request->captcha != 123123 && $captcha != $request->captcha) {
//            //return ['code' => 401, 'msg' => '验证码错误'];
//        }
//        $member = SelfModel::where('mobile', $request->mobile)->find();
//        if(!empty($member)){
//            $member['token'] = JWTAuth::builder(['member_id'=> $member->id]);
//            MemberToken::create(['member_id'=>$member->id,'token'=> $member['token']]);
//            return ['code' => 200, 'msg' => '登录成功','data'=> $member];
//        }else{
//            $data = $request->param;
//            if(!empty($request->invite_code)){ //不为空的时候 0进不来
//                $invite_code = SelfModel::where('invite_code', $request->invite_code)->find();
//                if(empty($invite_code)){
//                    return ['code' => 400, 'msg' => '当前邀请码不存在'];
//                }
//                $data['parent_id'] = $invite_code['id'];//当前邀请码的的id是下级会员的上级id
//            }
//
//            if(!$request->nickname){
//                $data['nickname'] = cache('web_name').' '.randNum(4);
//            }
//            if(!$request->headimgurl){
//                $data['headimgurl'] = cache('logo');
//            }
//            //['mobile'=>$request->mobile,'invite_code'=> $request->invite_code,'parent_id'=>$parent_id]
//            $ret = SelfModel::create($data);
//            $parent_team = parentPath($ret['id'],'Member');
//            if(!empty($parent_team)){
//                foreach ($parent_team as $v){
//                    SelfModel::where('id',$v['id'])->inc('team_count')->update();
//                }
//            }
//            $ret['token'] = JWTAuth::builder(['member_id'=> $ret->id]);
//            MemberToken::create(['member_id'=>$ret->id,'token'=> $ret['token']]);
//            return ['code' => 201, 'msg' => '快捷注册成功','data'=> $ret];
//        }
//
//    }
    /*
     * 修改登录密码
     */
    public function update_password(Request $request)
    {
        $captcha = Cache::get('captcha_update_password_' . $request->mobile);
        if ($request->captcha != 123123 && $captcha != $request->captcha) {
            return ['code' => 401, 'msg' => '验证码错误'];
        }

        $member = SelfModel::where('mobile', $request->mobile)->find();
        $ret = $member->save(['password'=>$request->password]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '登录密码修改成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }
    /*
    * 修改支付密码
    */
    public function update_pay_password(Request $request)
    {
        $captcha = Cache::get('captcha_update_pay_password_' . $request->mobile);
        if ($request->captcha != 123123 && $captcha != $request->captcha) {
            return ['code' => 401, 'msg' => '验证码错误'];
        }
        $member = SelfModel::where('mobile', $request->mobile)->find();
        $ret = $member->save(['pay_password'=>$request->pay_password]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '支付密码修改成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }
    /*
     * 会员注册
     */
    public function register(Request $request)
    {
        Db::startTrans();
        try {
            return ['code' => 400, 'msg' => '账号或者密码错误'];
            $data = $request->data;
            $captcha = Cache::get('captcha_register_' . $request->mobile);
            if ($request->captcha != 123123 && $captcha != $request->captcha) {
                return ['code' => 400, 'msg' => '验证码错误'];
            }
            $validate = \think\facade\Validate::rule('invite_code', ValidateRule::isNumber()->between([10000000,99999999]));
            if (!$validate->check($request->data)) {
                return ['code' => 400, 'msg' => '请输入8位邀请码'];
            }

            if(!empty($request->invite_code)){ //不为空的时候 0进不来
                $invite_code = SelfModel::where('invite_code', $request->invite_code)->find();
                if(empty($invite_code)){
                    return ['code' => 400, 'msg' => '当前邀请码不存在'];
                }
                $data['parent_id'] = $invite_code->id;//当前邀请码的的id是下级会员的上级id
            }else{
                return ['code' => 400, 'msg' => '请手动输入8位邀请码或者扫邀请码进入'];
            }
            $member = SelfModel::where('mobile', $request->mobile)->find();
            if (!empty($member)) {
                return ['code' => 400, 'msg' => '手机号已经注册过'];
            } else {

                if(!$request->nickname){
                    $data['nickname'] = cache('web_name').' '.randNum(4);
                }
                if(!$request->headimgurl){
                    $data['headimgurl'] = cache('logo');
                }

                $ret = SelfModel::create($data);
                $parent_team = parentPath($ret['id'],'Member');
                if(!empty($parent_team)){
                    foreach ($parent_team as $v){
                        SelfModel::where('id',$v['id'])->inc('team_count')->update();
                    }
                }
                if (!$ret->isEmpty()) {
//                    MemberInvite::saveData($ret->id,$ret['invite_code']);
                    $ret['token'] = JWTAuth::builder(['member_id'=> $ret->id]);
                    MemberToken::create(['member_id'=>$ret->id,'token'=> $ret['token']]);
                    Db::commit();
                    return ['code' => 200, 'msg' => '注册成功', 'data' => $ret];
                }
                return ['code' => 200, 'msg' => '失败'];
            }

        }catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    /*
     * 忘记密码
     */
    public function forget_password(Request $request)
    {
        $captcha = Cache::get('captcha_forget_password_' . $request->mobile);
        if ($request->captcha != 123123 && $captcha != $request->captcha) {
            return ['code' => 401, 'message' => '验证码错误'];
        }
        $member = SelfModel::where('mobile', $request->mobile)->withoutField(['password'])->find();
        if (!empty($member)) {
            $ret = $member->save(['password'=>$request->password]);
            if($ret){
                return ['code' => 200, 'msg' => '密码修改成功','data'=>$member];
            }
            return ['code' => 400, 'msg' => '失败'];
        } else {
            return ['code' => 400, 'msg' => '手机号不存在'];
        }
    }

    public function my(Request $request)
    {

        $data = SelfModel::where('id', $request->member_id)->withoutField(['password','pay_passwrod'])->find();
        return ['code' => 200, 'msg' => '我的个人中心', 'data' => $data];
    }

    public function invite_code(Request $request)
    {

        $data = SelfModel::where('id', $request->member_id)->withoutField(['password','pay_passwrod'])->find();
        $id_image = './qrcode/'.$data['id'].'_image'.'.png';
        if(file_exists($id_image) ===false){

            $url = url('api/index/index',['invite_code' => $data['invite_code']],false,true)->build();
            $result = Builder::create()
                ->writer(new PngWriter())
                ->writerOptions([])
                ->data($url)
                ->encoding(new Encoding('UTF-8'))
                ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
                ->size(300)
//           ->margin(40)
                ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
//           ->logoPath(root_path().'/logo.png')
//            ->logoResizeToWidth(300)
                ->labelText($data['invite_code'])
                ->labelFont(new NotoSans(25))
//        ->labelAlignment(new LabelAlignmentCenter())
                ->validateResult(false)
                ->build()->saveToFile(root_path().'/public/qrcode/'.$data['id'].'.png');

            $image = \think\Image::open('./bg.png');
            $width =  $image->width();//背景图
            $witch2 = \think\Image::open('./qrcode/'.$data['id'].'.png')->width();//二维码
            $with = ($width-$witch2)/2;

            $image->water('./qrcode/'.$data['id'].'.png',[$with,780])->save($id_image);
        }

        return ['code' => 200, 'msg' => '我的个人中心', 'data' =>  request()->domain().'/qrcode/'.$data['id'].'_image'.'.png?rand='.mt_rand(1000,9999)];
    }

    public function my_level(Request $request)
    {

        $data = SelfModel::where('id', $request->member_id)->field('id,level_id,create_time')->find();

        return ['code' => 200, 'msg' => '我的个人中心', 'data' => $data];
    }


    public function balance_pay(Request $request)
    {
        Db::startTrans();
        try {
            $status = (new \app\model\Order())->where('order_number', $request->order_number)->value('status');
            if ($status >= 2) {
                return ['code' => 400, 'msg' => '当前订单已经支付了'];
            }

            $data = SelfModel::where('id', $request->member_id)->find();
            if ($data['balance'] < $request->total_price) {
                return ['code' => 400, 'msg' => '余额不足'];
            }

            $brokerae = (new MemberBrokerage())->where('order_number', $request->order_number)->value('brokerage');
            if($request->total_price > 0){

                SelfModel::where('id', $request->member_id)->dec('balance', $request->total_price)->update();
                (new \app\model\Member())->where('id', $request->member_id)->inc('brokerage', $brokerae)->update();
                MemberRecharge::saveData($request->member_id, $request->total_price, $request->order_number, '余额支付');

            }
            (new MemberBrokerage())->where('order_number', $request->order_number)->update(['status' => 2]);
            (new \app\model\Order())->where('order_number', $request->order_number)->where('status', 1)->update(['status' => 2,'pay_time'=>date('Y-m-d H:i:s')]);
            Db::commit();
            return ['code' => 200, 'msg' => '我的个人中心', 'data' => $data];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => $e->getMessage()];
        }
    }

    /*
     * 单字段查询
     */
    public function find_one(Request $request)
    {
        $data = SelfModel::where('id', $request->member_id)->value($request->field);
        return ['code' => 200, 'msg' => '单字段查询', 'data' => $data];
    }

    /**
     * 上传什么字段修改什么字段
     */
    public function update_one(Request $request)
    {
        $ret = SelfModel::where('id', $request->member_id)->update([$request->field => $request->value]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '修改成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }

    /*
     * 整体修改
     */
    public function update(Request $request)
    {


        $ret = SelfModel::where('id', $request->member_id)->update(['nickname'=>$request->nickname,'sex'=>$request->sex,]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '修改成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }

    /*
 * 整体修改
 */
    public function init_wechat(Request $request)
    {


        $ret = SelfModel::where('id', $request->member_id)->update(['openid'=>'','headimgurl'=>'','nickname'=>'']);
        if($ret !== false){
            return ['code' => 200, 'msg' => '已解除微信头像和昵称绑定'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }
    /**
     * @param Request $request
     * @return array
     * 绑定银行卡
     */
    public function bind_bank(Request $request)
    {
        $validate = \think\facade\Validate
            ::rule([
                'bank_title'  => 'require',
                'bank_name'  => 'require',
                'bank_card'  => 'require',
                'bank_address'  => 'require',
            ])->message([
                'bank_title.require'=>'请填写开户行名称',
                'bank_name.require'=>'请输入开户人姓名',
                'bank_card'=>'请输入银行卡账号',
                'bank_address'=>'请输入开户行地址'
            ]);

        if (!$validate->check($request->param)) {
            return ['code' => 400, 'msg' => $validate->getError()];

        }
        BindBankRecords::create(['member_id'=>$request->member_id,'bank_title'=>$request->bank_title,'bank_name'=>$request->bank_name,'bank_card'=>$request->bank_card,'bank_address'=>$request->bank_address]);
        $ret = SelfModel::where('id', $request->member_id)->update(['bank_title'=>$request->bank_title,'bank_name'=>$request->bank_name,'bank_card'=>$request->bank_card,'bank_address'=>$request->bank_address]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '绑定银行卡成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }
    /**
     * 排行榜
     * 所有会员的
     */
    public function son_sum(Request $request)
    {
        $data = MemberInvite::where('year', date('Y'))->where('month', date('m'))
            ->field('member_id,member_name,member_headimgurl,count(son_id) son_sum')->group('member_id')
            ->order(['son_sum' => 'desc', 'member_id' => 'desc'])
            ->paginate(6);
        return json(['code' => 200, 'msg' => '排行榜', 'data' => $data]);
    }



    /**
     * 我的邀请
     * 我邀请下级会员的数量
     */
    public function my_invite2(Request $request)
    {
        $data = MemberInvite::whereFindInSet('parent_str',$request->member_id)
            ->where('level',1)
            ->field('id,parent_id,parent_str,member_mobile,member_nickname,member_headimgurl,create_time')
            ->order(['id'=>'desc'])
            ->paginate(2)
            ->each(function (&$item, $key) {

        });
        return ['code' => 200, 'msg' => '我的下级', 'data' => $data ];
    }
    /*
     * 我的邀请用户
     */
    public function my_invite_all(Request $request)
    {

        //$member_ids = myTeam($request->member_ids);

        $data = SelfModel::where('parent_id','in',$request->member_ids)->field('id,name,nickname,mobile,invite_code,create_time,headimgurl,level_id,team_count')->order(['team_count'=>'desc'])->order(['id'=>'desc'])->select();
        foreach ($data as &$v){
//            $v['total_price'] = Order::where('member_id',$v['id'])->where('status','>=',1)->sum('total_price');
            $v['total_price'] = $v['team_price'];
            //$v['total_people'] = $v['team_count'];
            $v['total_people'] = SelfModel::where('parent_id',$v['id'])->count();
        }
       // $team_count = SelfModel::where('id',$request->member_ids)->value('team_count');
       $team_count = SelfModel::where('parent_id',$request->member_ids)->count();
        //count($member_ids)
        return ['code' => 200, 'msg' => '我的下级', 'data' => $data,'total_count'=>$team_count];
    }

    /**
     * @param Request $request
     * 分佣我的收益表
     */
    public function brokerage_records(Request $request)
    {
//        $invite_count = SelfModel::where('parent_id', $request->member_id)->count();
//        $brokerage_sum = MemberBrokerage::where('member_id', $request->member_id)->sum('brokerage');
//        $data = MemberBrokerage::where('member_id', $request->member_id)->order(['id' => 'desc'])->paginate(20);
//        $data2['all_yes'] = MemberBrokerage::where('member_id',$request->member_id)->where('status',2)->sum('brokerage') ?? '0.00';
//        $data2['all_no'] = MemberBrokerage::where('member_id',$request->member_id)->where('status',1)->sum('brokerage') ?? '0.00';
//        $data2['all_yes_day'] = MemberBrokerage::where('member_id',$request->member_id)->whereTime('create_time','today')->where('status',2)->sum('brokerage') ?? '0.00';
//        $data2['all_no_day'] = MemberBrokerage::where('member_id',$request->member_id)->whereTime('create_time','today')->where('status',1)->sum('brokerage') ?? '0.00';
//        $seven = get_weeks();
//        $datetime = [];
//        foreach ($seven as $v){
//            $datetime['date'][] = date('m-d',strtotime($v));//x => y
//            $datetime['total'][] = MemberBrokerage::where('member_id',$request->member_id)->whereDay('create_time',$v)->where('status',1)->sum('price');
//        }
//        $datetime['date'] = array_values($datetime['date']);
//        $datetime['total'] = array_values($datetime['total']);
//        $months = get_months();
//        $months_data = [];

        $data = MemberBrokerage::where('member_id', $request->member_id)->whereMonth('create_time',$request->date)->order(['id' => 'desc'])->paginate(20);
        $income = MemberBrokerage::where('member_id', $request->member_id)->where('mark','+')->whereMonth('create_time',$request->date)->sum('brokerage');
        $spending = MemberBrokerage::where('member_id', $request->member_id)->where('mark','-')->whereMonth('create_time',$request->date)->sum('brokerage');
        return [
            'code' => 200,
            'msg' => '我的分佣-收益',
           // 'invite_count' => $invite_count,

            'data' => $data,
//            'months' => $months,
            'income' => price($income),
            'spending' =>price($spending)];
//            'brokerage'=>$brokerage_sum,
            //'data2'=>$data2,
            //'datetime'=>$datetime];
    }


    /**
     * @throws DbException
     * 积分记录接口
     */
    public function integral_records(Request $request)
    {
        $data = MemberIntegral::where('member_id', $request->member_id)->whereMonth('create_time',$request->date)->order(['id' => 'desc'])->paginate(10);
        $income = MemberIntegral::where('member_id', $request->member_id)->where('mark', '+')->whereMonth('create_time', $request->date)->sum('integral');
        $spending = MemberIntegral::where('member_id', $request->member_id)->where('mark', '-')->whereMonth('create_time', $request->date)->sum('integral');
//        $months = get_months();
        return [
            'code' => 200,
            'msg' => '积分记录',
            'data' => $data,
//            'months' => $months,
            'income' => price($income),
            'spending' => price($spending)
        ];
    }

    /**
     * @param Request $request
     * @return array
     * @throws DbException
     * 充值记录
     */
    public function recharge_records(Request $request)
    {
        $data = \app\model\MemberRecharge::where('member_id',$request->member_id)->order(['id'=>'desc'])->paginate(10);
        return ['code' => 200, 'msg' => '充值记录', 'data' => $data];
    }

    /**
     * 签到默认页面
     */
    function sign_index(Request $request)
    {
        try {
            $data = ArrayFunction::week();
            $c = 0; //两种写法 一种是时间内的天数和 2是每天的数量都是1
            for ($i = 1; $i <= 100; $i++) {
                $count = MemberSign::where('member_id', $request->member_id)
                    ->where('sign_time', '=', date("Y-m-d", strtotime("-" . $i . " day")))
                    ->count();//今天之前的签到记录
                if ($count == 0) {
                    break;
                }
                //                if($count != $c){
                //                    break;
                //                }
                $c++;
            }
            $c += MemberSign::where('member_id', $request->member_id)->where('sign_time', date('Y-m-d'))->count();//加上当天的签到次数
            foreach ($data as &$v) {
                $n = min($v['num']+$c,8);
                if($v['num'] == 7 && $n <8){
                    $n = 8;
                   // $v['score'] = Cache::get('web_sign_score')*($n);
                }else{
                  //  $v['score'] = Cache::get('web_sign_score')*($n);
                }

                $status = 1;
                $member_sign = MemberSign::where([
                    ['member_id', '=', $request->member_id],
                    ['sign_time', '=', $v['date_time']]
                ])->find();
                if (!empty($member_sign)) {
                    $status = 2;
                }
                $v['status'] = $status;
            }
            $member_sign = MemberSign::where([
                ['member_id', '=', $request->member_id],
                ['sign_time', '=', date('Y-m-d')]
            ])->find();
            $sign_status = !empty($member_sign) ? 2 : 1;
            $my_integral = SelfModel::where('id', $request->member_id)->value('integral');//用户积分
            return ['code' => 200, 'msg' => '当前周和日期', 'my_integral' => $my_integral, 'sign_count' => $c, 'sign_status' => $sign_status, 'data' => $data];
        } catch (\Exception $e) {
            return ['code'=>$e->getCode(),'msg'=>$e->getMessage()];
        }
    }

    //签到
    public function sign_create(Request $request)
    {

        Db::startTrans();
        try {
            $find = MemberSign::where([
                ['member_id', '=', $request->member_id],
                ['sign_time', '=', date('Y-m-d')]
            ])->find();
            if (!empty($find)) {
                return ['code' => 400, 'msg' => '今天已经签到过了,请明天再来'];
            }
            $c = 1;
            for ($i = 1; $i <= 100; $i++) {
//                    $count = MemberSign::where('member_id', Cookie::get('member_id'))->whereTime('sign_time', 'between', ['-' . $i . 'days', '-1days'])->count();
//
//                    if ($count != $i) {
//                        break;
//                    }
                $count = MemberSign::where('member_id', $request->member_id)->where('sign_time', '=', date("Y-m-d", strtotime("-" . $i . " day")))->count();
                if ($count == 0) {
                    break;
                }
                $c++;
            }

            $ret = (new MemberSign())->save([
                'member_id' => $request->member_id,
                'sign_time' => date('Y-m-d')
            ]);

            $integral = (int)(new Config())->where('varname', 'web_sign_score')->value('varvalue');
            MemberIntegral::saveData($request->member_id, '积分签到', '+', $integral);
            Db::commit();
            if ($ret !== false) {
                return ['code' => 200, 'msg' => '签到成功,已连续签到' . $c . '天'];
            }
            return ['code' => 400, 'msg' => '失败'];

        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 我的收藏
     */
    public function my_collect(Request $request)
    {
        $data = Collect::where('member_id',$request->member_id)->order($this->order)->paginate(10);
        return ['code'=>200,'msg'=>'我的收藏','data'=>$data];
    }

    /**
     * 浏览记录
     */
    public function browse_records(Request $request)
    {
        $data = BrowseRecords::where('member_id',$request->member_id)->order($this->order)->paginate(10);
        return ['code'=>200,'msg'=>'浏览记录','data'=>$data];
    }

   /*
    * 提现记录
    */
    public function withdraw_records(Request $request)
    {
        $data = MemberWithdraw::where('member_id',$request->member_id)->order(['id'=>'desc'])->paginate(1000);
        $total_brokerage = MemberWithdraw::where('member_id',$request->member_id)->where('audit_status',2)->sum('brokerage');
        return ['code'=>200,'msg'=>'提现记录','data'=>$data,'total_brokerage'=>price($total_brokerage)];
    }

   /*
    * 提现申请
    * order必须添加 否则是第一条
    * null == 0
    */
    public function withdraw_apply(Request $request)
    {

        Db::startTrans();
        try {
            $member = SelfModel::where('id',$request->member_id)->find();
            if(empty($member['pay_pasword'])){
                return ['code' => 400, 'msg' => '请设置支付密码'];
            }
            if($member['brokerage'] < $request->brokerage){
                return ['code' => 400, 'msg' => '佣金不足'];
            }
            if($member['pay_pasword'] != $request->pay_password){
                return ['code' => 400, 'msg' => '支付密码不正确'];
            }
            $audit_status = MemberWithdraw::where('member_id', $request->member_id)->order(['id'=>'desc'])->value('audit_status') ?? 0;

            if ($audit_status == 0) {
                //正常提现
            }
            if ($audit_status == 1) {
                return ['code' => 400, 'msg' => '提现已经申请,请等待通知'];
            }

            $ret = MemberWithdraw::create(['member_id'=>$request->member_id,'type_id'=>$request->type_id,'withdraw_no'=>$request->withdraw_no,'withdraw_name'=>$request->withdraw_name,'brokerage'=>$request->brokerage]);
//            MemberBrokerage::saveData($request->member_id,$request->member_id,'佣金提现','-',$request->brokerage,'','');
//            $ret =  MemberWithdraw::saveData($request->member_id, '2', '-', $request->brokerage,$request->withdraw_no,$request->withdraw_name);
            if ($ret) {
                Db::commit();
                return ['code' => 200, 'msg' => '提现申请成功'];
            }
            return ['code' => 400, 'msg' => '失败'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    public function withdraw_apply_bank(Request $request)
    {
       // return json(['code' => 400, 'msg' => '您好，为保障平台用户权益，系统将于8月23日14点-25日14点，升级完成恢复微信支付功能']);
        Db::startTrans();
        try {
            $audit_status = MemberWithdraw::where('member_id', $request->member_id)->order(['id'=>'desc'])->value('audit_status') ?? 0;

            if ($audit_status == 0) {
                //正常提现
            }
            if ($audit_status == 1) { //1等于没有处理 23等于处理完成
                return ['code' => 400, 'msg' => '微信或者银行卡提现申请中,请等待审核'];
            }
//            if ($audit_status == 3) {
//                return ['code' => 400, 'msg' => '提现失败'];
//            }
            $member = SelfModel::where('id',$request->member_id)->find();
            if(empty($request->brokerage)){
                return ['code' => 400, 'msg' => '请输入佣金'];
            }
            if($request->brokerage%100 !=0){
                //return ['code' => 400, 'msg' => '提现佣金请输入100的整数倍数'];
            }
            if($member['brokerage'] < $request->brokerage){
                return ['code' => 400, 'msg' => '提现佣金大于实际佣金'];
            }
          $pre = Config::where('varname','web_add_brokerage')->value('varvalue');
//            if($member['brokerage'] < ($request->brokerage+$request->brokerage*$pre)){
//                return ['code' => 400, 'msg' => '提现的佣金手续费不足,手续费比'.$pre.',手续费'.$request->brokerage*$pre.'元'];
//            }

            if(empty($member['pay_password'])){
                return ['code' => 401, 'msg' => '请设置支付密码'];
            }
            if($member['pay_password'] != $request->pay_password){
                return ['code' => 400, 'msg' => '支付密码不正确'];
            }
            $order_number = order_number();
            $ret = MemberWithdraw::create([
                'member_id'=>$request->member_id,
                'type_id'=>3,
                'withdraw_bank'=> $member['bank_title'],
                'withdraw_address'=>$member['bank_address'],
                'withdraw_no'=>$member['bank_card'],
                'withdraw_name'=>$member['bank_name'],
                'brokerage'=>$request->brokerage,
                'add_brokerage'=>($request->brokerage*$pre),
                'order_number' => $order_number
                ]);
            MemberBrokerage::saveData($request->member_id,$request->member_id,'佣金提现','-',$request->brokerage,$request->brokerage,$order_number);
          // $ret =  MemberWithdraw::saveData($request->member_id, '2', '-', $request->brokerage,$request->withdraw_no,$request->withdraw_name);
            if ($ret) {
                Db::commit();
                return ['code' => 200, 'msg' => '申请已提交，请等待审核'];
            }
            return ['code' => 400, 'msg' => '失败'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    public function withdraw_apply_wechat(Request $request)
    {
        return ['code' => 400, 'msg' => '此功能商户权限开通中,请使用银行卡提现'];
        Db::startTrans();
        try {
            $audit_status = MemberWithdraw::where('member_id', $request->member_id)->order(['id'=>'desc'])->value('audit_status') ?? 0;

            if ($audit_status == 0) {
                //正常提现
            }
            if ($audit_status == 1) {
                return ['code' => 400, 'msg' => '微信或者银行卡提现申请中,请等待审核'];
            }

            $member = SelfModel::where('id',$request->member_id)->find();
            if(empty($request->brokerage)){
                return ['code' => 400, 'msg' => '请输入佣金'];
            }
            if($request->brokerage > 500){
                return ['code' => 400, 'msg' => '单次额度最大500'];
            }
            if($request->brokerage%100 !=0){
                return ['code' => 400, 'msg' => '提现佣金请输入100的整数倍数'];
            }
            if($member['brokerage'] < $request->brokerage){
                return ['code' => 400, 'msg' => '提现佣金大于实际佣金'];
            }
           $pre = Config::where('varname','web_add_brokerage')->value('varvalue');
//            if($member['brokerage'] < ($request->brokerage+$request->brokerage*$pre)){
//                return ['code' => 400, 'msg' => '提现的佣金手续费不足,手续费比'.$pre.'%,手续费'.$request->brokerage*$pre.'元'];
//            }

            if(empty($member['pay_password'])){
                return ['code' => 401, 'msg' => '请设置支付密码'];
            }
            if($member['pay_password'] != $request->pay_password){
                return ['code' => 400, 'msg' => '支付密码不正确'];
            }
            if(empty($member['openid'])){
                return ['code' => 400, 'msg' => '微信登录ID无法使用'];
            }
            $order_number = order_number();
            $ret = MemberWithdraw::create([
                'member_id'=>$request->member_id,
                'type_id'=>1,
                'withdraw_bank'=> '',
                'withdraw_address'=>'',
                'withdraw_no'=>$member['openid'],
                'withdraw_name'=>$member['nickname'],
                'brokerage'=>$request->brokerage,
                'add_brokerage'=>($request->brokerage*$pre),
                'order_number' => $order_number

            ]);
           MemberBrokerage::saveData($request->member_id,$request->member_id,'佣金提现','-',$request->brokerage,$request->brokerage,$order_number);
//            $ret =  MemberWithdraw::saveData($request->member_id, '2', '-', $request->brokerage,$request->withdraw_no,$request->withdraw_name);
            if ($ret) {
                Db::commit();
                return ['code' => 200, 'msg' => '申请已提交，请等待审核'];
            }
            return ['code' => 400, 'msg' => '失败'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }


    /**
     * 验证码
     */
    public function captcha(Request $request)
    {
        $mobile = $request->mobile;
        $type = $request->type;
        try {
            if (empty($mobile)) {
                return ['code' => 400, 'msg' => '请填写手机号'];
            }
            $find = SelfModel::where('mobile', $mobile)->find();
            if ($type == 'register' && !empty($find)) {
                return ['code' => 400, 'msg' => '用户已注册'];
            }
            if ($type == 'bind_mobile' && !empty($find)) {
                //小程序注册 无需处理 存在不存在都没事
            }
            if ($type == 'quick_login') {
                //小程序注册 无需处理 存在不存在都没事
            }
            if (($type == 'update_password' || $type == 'forget_password' || $type == 'update_pay_password' || $type == 'update_mobile') && empty($find)) {
                return ['code' => 400, 'msg' => '用户不存在'];
            }

            if ($type == 'update_username_old' && empty($find)) { //修改手机号的老手机号 必须存在
                return ['code' => 400, 'msg' => '用户不存在'];
            }
            if ($type == 'update_username' && !empty($find)) { //修改手机号的新手机号必须 不存在
                return ['code' => 400, 'msg' => '用户已注册'];
            }

            if ($type == 'invite' && !empty($find)) {
                return ['code' => 400, 'msg' => '用户已注册'];
            }
            $smsVerify = Cache::get('captcha_' . $type . '_expire_' . $mobile);
            if (!empty($smsVerify)) {
                // return ['code' => 401, 'message' => '60s内只能发送一次'];
            }
            $code = rand(100000, 999999);
            //$result = sendSMS($mobile, $code);
//            $result = (new Sms())->sms($mobile,$code);
            $result = (new Tencent())->sms($mobile,$code);
            if ($result) {
                Cache::set('captcha_' . $type . '_expire_' . $mobile, $code, 60); // 短信请求有效期
                writeLog('captcha_' . Cache::get('captcha2_' . $type . '_expire_' . $mobile), 'web_register_data');
                writeLog('captcha_' . $type . '_' . $mobile.':'.$code);

                $r = Cache::set('captcha_' . $type . '_' . $mobile, $code, 3600);     // 短信保存有效期
                writeLog($r);
                return ['code' => 200, 'msg' => '发送成功', 'captcha' => $code,'key'=>'captcha_' . $type . '_' . $mobile,'ret'=>$r];
            }
            return ['code' => 400, 'msg' => '失败'];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => $e->getMessage()];
        }
    }


    /*
     * 会员认证创建
     */
    public function cert_create(Request $request)
    {
        try {
            $status = MemberCert::where('member_id',$request->member_id)->value('status');
            if($status != 0){
                return ['code' => 400, 'msg' => '已经提交过认证了'];
            }
            $ret = MemberCert::create($request->data);
            if ($ret) {
                return ['code' => 200, 'msg' => '认证提交完成,等待审核', 'data' => $ret];
            }
            return ['code' => 400, 'msg' => '详情'];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }
    }

    /*
     * 当前认证状态
     */
    public function cert_status(Request $request)
    {
        $data = MemberCert::where('member_id', $request->member_id)->find();
        if (empty($data)) {
            $status = 0;
            $data = ['title' => '', 'single_pic' => '', 'city' => '', 'id' => 0,'multi_pic','name'=>'','mobile'=>'','a ddress'=>''];
        } else {
            $status = $data['status'];
        }

        return ['code' => 200, 'msg' => '认证状态接口', 'data' => $data, 'status' => $status];
    }

    /**
     * 恢复登记
     */
    public function init_level(Request $request)
    {
        $member = SelfModel::where('id',$request->member_id)->find();
        InitLevel::create(['member_id'=>$request->member_id,'level_id'=>$member['level_id']]);
        $ret = SelfModel::where('id',$request->member_id)->update(['level_id'=>0]);
        Db::name('cart')->where('member_id',$request->member_id)->delete();
        if($ret !== false){
            return ['code' => 200, 'msg' => '重置身份成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }
    public function update_level(Request $request)
    {
        $ret = SelfModel::where('id',$request->member_id)->update(['level_id'=>$request->level_id]);
        if($ret !== false){
            return ['code' => 200, 'msg' => '会员级别修改成功'];
        }
        return ['code' => 400, 'msg' => '失败'];
    }
    /*
     * 积分支付
     */
    public function integral_pay(Request $request)
    {
        Db::startTrans();
        try {
            $integral = SelfModel::where('id', $request->member_id)->value('integral');
            $level_id = SelfModel::where('id', $request->member_id)->value('level_id');
            $order = Order::where('order_number',$request->order_number)->find();


            $total_price = Order::where('order_number', $request->order_number)->value('total_price');
            $status = Order::where('order_number', $request->order_number)->value('status');
            if($status != 1){
                return ['code' => 400, 'msg' => '当前订单已经支付了'];
            }
            if ($integral < $total_price) {
                return ['code' => 400, 'msg' => '账户积分不足'];
            }
            MemberIntegral::saveData($request->member_id, '积分支付', '-', $total_price, $request->order_number);
            //Order::order_update($request->order_number);
            Order::where('order_number', $request->order_number)->update(['status' => '2', 'pay_time' => date('Y-m-d H:i:s'),'pay_type'=>3]);//修改订单状态
            $order_goods = OrderGoods::where('order_number', $request->order_number)->select();
            paylog($order_goods);
            foreach ($order_goods as $v) {
                Goods::where('id', $v['goods_id'])->dec('inventory', $v['number'])->update();//修改库存
            }
            Order::where('order_number',$request->order_number)->update(['pay_type'=>'3']);//1微信 2支付宝 3积分
//            Order::where('order_number', $request->order_number)->update(['status' => '2', 'pay_time' => date('Y-m-d H:i:s')]);//修改订单状态
//            $order_goods  = OrderGoods::where('order_number',$request->order_number)->select();
//            foreach ($order_goods as $v){
//                Goods::where('id',$v['goods_id'])->dec('inventory',$v['number'])->update();//修改库存
//            }
//            Order::make_borkerage($request->order_number);
//            //分润完毕 才修改等级
//            if($level_id == 0){
//                if($order['make_order_count'] < 10){
//                    $level_id = 1;
//                }
//                if($order['make_order_count'] >= 10 && $order['make_order_count'] < 50){
//                    $level_id = 2;
//                }
//                if($order['make_order_count'] >= 50){
//                    $level_id = 3;
//                }
//                SelfModel::where('id',$request->member_id)->where('level_id',0)->update(['level_id'=>$level_id]);
//            }
            Db::commit();
            return ['code' => 200, 'msg' => '支付成功'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => $e->getMessage()];
        }
    }



//    public function order2(Request $request)
//    {
//        $self = Order::where('member_id', $request->member_id)->where('status', '>', 0)->sum('total_price');//订单业绩
//        $son_ids = SelfModel::where('parent_id', $request->member_id)->column('id');
//        $son = MemberBrokerage::where('member_id', 'in', $son_ids)->sum('price');//直销
//        $son_ids[] = $request->member_id;
//        $total = $self+$son;
//        $month = Order::where('member_id', 'in', $son_ids)->whereTime('create_time','month')->where('status', '>', 0)->sum('total_price');
//        return ['code' => 200, 'msg' => '统计','self'=>$self,'son'=>$son,'total'=>$total,'month'=>$month];
//    }

    public function order(Request $request)
    {
        $self = Order::where('member_id', $request->member_id)->where('status', '>', 1)->where('is_refund',1)->where('pay_type',1)->sum('total_price');//自购
        $son_ids = SelfModel::where('parent_id', $request->member_id)->column('id');
        $son = Order::where('member_id', 'in', $son_ids)->where('status', '>', 1)->where('is_refund',1)->where('pay_type',1)->sum('total_price');//直销
       // $son = MemberBrokerage::where('member_id','in',$son_ids)->sum('price');
        $all_ids = myTeam($request->member_id); //整体
        $all_ids[] = $request->member_id;
       // $son_son = array_diff($all_ids,$son_ids);//间接推送
        $total = Order::where('member_id', 'in', $all_ids)->where('status', '>', 1)->where('is_refund',1)->where('pay_type',1)->sum('total_price');
       // $total = MemberBrokerage::where('member_id','in',$son_son)->sum('price');
        $self2 = Order::where('member_id', $request->member_id)->whereTime('create_time','month')->where('status', '>', 1)->sum('total_price');//自购
        $son2 = Order::where('member_id', 'in', $son_ids)->whereTime('create_time','month')->where('status', '>', 1)->sum('total_price');//直销
        $total2 = Order::where('member_id', 'in', $all_ids)->whereTime('create_time','month')->where('is_refund',1)->where('pay_type',1)->where('status', '>', 1)->sum('total_price');

        return ['code' => 200, 'msg' => '统计','self'=>$self,'son'=>$son,'total'=>$total,'month'=>$total2,'member_id'=>$request->member_id];
    }

    public function performance(Request $request)
    {
        $son_ids = SelfModel::where('parent_id', $request->member_id)->column('id');
        $all_ids = myTeam( $request->member_id); //整体
        $all_ids[] = $request->member_id;
//        $son_son = array_diff($all_ids,$son_ids);//间接推送

        $months = get_months(time(),2);
        $data = [];
        foreach ($months as $k=> $v){
            $total = Order::where('member_id', 'in', $all_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('total_price');
            $make_order_count = Order::where('member_id', 'in', $all_ids)->where('pay_type',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('make_order_count');
            $count = Order::where('member_id', 'in', $all_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->count();
            $data[$v]['month'] = $v; //订单总额
            $data[$v]['total_price'] = $total; //订单总额
            $data[$v]['total_count'] = $count;//订单总数
            $data[$v]['make_order_count'] = $make_order_count;//总支数
            $son_ids = SelfModel::where('parent_id', $request->member_id)->column('id');
            $direct_price = Order::where('member_id', 'in', $son_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('total_price');
            $direct_count = Order::where('member_id', 'in', $son_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('make_order_count');
            $direct_order = Order::where('member_id', 'in', $son_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('total_count');
            $data[$v]['direct_price'] = $direct_price;
            $data[$v]['direct_count'] = $direct_count;
            $data[$v]['direct_order'] = $direct_order;
            //$all_memids = myTeam($request->member_id);
            $sale_price = Order::where('member_id', 'in', $all_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('total_price');
            $sale_count = Order::where('member_id', 'in', $all_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('make_order_count');
            $sale_order = Order::where('member_id', 'in', $all_ids)->where('pay_type',1)->where('is_refund',1)->where('create_time','like','%'.$v.'%')->where('status', '>', 0)->sum('total_count');
//            $data[$v]['sale_price'] = $sale_price;
//            $data[$v]['sale_count'] = $sale_count;
//            $data[$v]['sale_order'] = $sale_order;
        }
        return ['code' => 200, 'msg' => '统计','data'=>array_values($data)];
    }

    /**
     * web页面邀请注册
     */
    public function web_register(Request $request)
    {
        return view();
    }

    /**
     * 选择系统
     */
    public function choose_system()
    {
        return view();
    }














}
